<script setup lang='ts'>
import { ref, reactive, nextTick } from "vue"
import { storeToRefs } from "pinia"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { merchantSaveOrUpdateApiPost, merchantDetailApiGet, merchantDeleteAttachmentApiDelete, merchantSaveOrUpdateAttachmentApiPost } from "@/api/userMangement"
import { attachmentUploadApiPost } from "@/api/product.ts"
import { useColorStore } from "@/store/common"
import { useEnumStore } from "@/store/enumeration"
import useInstance from '@/hooks/useInstance';
import upLoadImgSingle from "@/components/upLoadImgSingle.vue"


const imgUpload1 = ref()
const imgUpload2 = ref()
const imgUpload3 = ref()
const provinceData = useColorStore()
const { province, selectProvinceCity } = storeToRefs(provinceData)
const { productType } = storeToRefs(useEnumStore())



const { filterData } = provinceData
defineOptions({
    name: 'addBusiness'
})
const emit = defineEmits(['refresh','searchEdit'])
const { global } = useInstance();
const dialogBasic = ref({
    title: "新建渠道商",
    visible: false,
    width: 700,
    height: 350,
    showFooter: true,
    marginTop: "12vh",
})

const ruleFormRef = ref<FormInstance>()
const ruleImgRef = ref<FormInstance>()
const active = ref(0)
const addOrEdit = ref()
const channelForm = reactive<any>({
    channelMerchantType: null, //  渠道商类型
    channelMerchantCode: null, //  渠道商编码 新增没有 后期通过id 查询 
    channelMerchantName: null, //  渠道商名称
    contactName: null, //  渠道商联系人
    contactMobile: null, //  渠道商联系人手机号
    corporationName: null, //  渠道商法人
    corporationCertNo: null, //  渠道商法人证件号
    locationProvinceCode: null, //   所在地-省
    locationProvinceName: null, //   所在地-省
    locationCityCode: null, //   所在地-市
    locationCityName: null, //  所在地-市
    uscc: null, //  统一社会信用代码
    remarks: null, //  备注
})
const rules = reactive<FormRules>({

    channelMerchantType: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择渠道类型"
        },
    ],
    channelMerchantName: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入渠道商名称"
        },
    ],
    contactName: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入渠道商联系人"
        },
    ],
    contactMobile: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入渠道商联系人手机号"
        },
        {
            trigger: 'blur',
            message: "请输入正确的手机号",
            pattern: /^1[3-9]\d{9}$/
        }
    ],
    corporationName: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入渠道商法人"
        },
    ],
    corporationCertNo: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入渠道商法人证件号"
        },
        {
            trigger: 'blur',
            pattern: /^(\d{17})([0-9Xx])$/i,
            message: "请输入正确的渠道商法人证件号"
        }
    ],
    locationProvinceCode: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入所在地-省"
        },
    ],
    locationCityCode: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择所在地-市"
        },
    ],
    uscc: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入统一社会信用代码"
        },
        // {
        //     trigger: 'blur',
        //     message: "请输入正确的统一社会信用代码",
        //     pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/
        // }
    ],




})
const ImgForm = reactive<any>({
    one: {
        channelMerchantCode: null, // 渠道商编码
        attachmentType: 1, // 附件类型 1 正面 2 反面 3 营业执照
        attachmentName: null, // 附件名称
        attachmentAliasName: null, // 附件别名
        attachmentUri: null, // 附件地址
    },
    two: {
        channelMerchantCode: null, // 渠道商编码
        attachmentType: 2, // 附件类型 1 正面 2 反面 3 营业执照
        attachmentName: null, // 附件名称
        attachmentAliasName: null, // 附件别名
        attachmentUri: null, // 附件地址
    },
    three: {
        channelMerchantCode: null, // 渠道商编码
        attachmentType: 3, // 附件类型 1 正面 2 反面 3 营业执照
        attachmentName: null, // 附件名称
        attachmentAliasName: null, // 附件别名
        attachmentUri: null, // 附件地址
    },
})
const imgRules = reactive({
})
// 图片上传数据 后期删除使用 
const blackSuccess = ref({
    one: null,
    two: null,
    three: null,
    basic: null
})
//显示弹框
const show = (type: string, row?: any) => {
    selectProvinceCity.value = null
    dialogBasic.value.visible = true
    // resetForm()
    if (type === 'add') {
        dialogBasic.value.title = "渠道商新增"
        dialogBasic.value.height = 600
        global.$resetForm(ruleFormRef.value, channelForm)
        addOrEdit.value = 'add'

    } else {
        addOrEdit.value = 'edit'
        dialogBasic.value.height = 600

        global.$resetForm(ruleFormRef.value, channelForm)
        dialogBasic.value.title = "渠道商编辑"
        global.$objCopy(channelForm, row)
        // 后期说图片的情况
        blackSuccess.value.one = row.attachmentList[0]?.id
        blackSuccess.value.two = row.attachmentList[1]?.id
        blackSuccess.value.three = row.attachmentList[2]?.id

        blackSuccess.value.basic = row.id
        filterData(1, null, row.locationProvinceCode)
        // 附件赋值 0 1 2 3 
        const indexArr = ["one", "two", "three"]
        row.attachmentList.forEach((item: any, index: number) => {
            if (index <= 2) {
                ImgForm[indexArr[index]].channelMerchantCode = item.channelMerchantCode
                ImgForm[indexArr[index]].attachmentName = item.attachmentName
                ImgForm[indexArr[index]].attachmentAliasName = item.attachmentAliasName
                ImgForm[indexArr[index]].attachmentUri = item.attachmentUri
            }

        })
        nextTick(() => {
            row.attachmentList.forEach((item: any, index: number) => {
                if (index == 0) {
                    imgUpload1.value.newUrl(row.attachmentList[0]?.attachmentUri, true)
                }
                if (index == 1) {
                    imgUpload2.value.newUrl(row.attachmentList[1]?.attachmentUri, true)
                }
                if (index == 2) {
                    imgUpload3.value.newUrl(row.attachmentList[2]?.attachmentUri, true)
                }
            })
        })
    }
}
const onClose = () => {
    selectProvinceCity.value = null
    active.value = 0
    dialogBasic.value.visible = false
    resetForm()
    Object.keys(channelForm).forEach(item => channelForm[item] = null)
    Object.keys(ImgForm).map(it => {
        ImgForm[it].channelMerchantCode = null
        ImgForm[it].attachmentName = null
        ImgForm[it].attachmentAliasName = null
        ImgForm[it].attachmentUri = null
    })
    imgUpload1.value.clearFile()
    imgUpload2.value.clearFile()
    imgUpload3.value.clearFile()
}
const onConfirm = async () => {
    await ruleFormRef.value?.validate(async isOk => {

        if (isOk) {
            const res = await merchantSaveOrUpdateApiPost(channelForm)
            if (res.code == 20000) {
                ElMessage({
                    type: "success",
                    message: channelForm.id ? "渠道商编辑基础数据成功" : "渠道商新增基础数据成功！"
                })
                active.value++
                setTimeout(async () => {
                    const nowRes = await merchantDetailApiGet({ id: res.data })
                    // 最新的数据 直接给第一个表单
                    global.$objCopy(channelForm, nowRes.data)
                    blackSuccess.value.basic = res.data
                    ImgForm.one.channelMerchantCode = nowRes.data.channelMerchantCode
                    ImgForm.two.channelMerchantCode = nowRes.data.channelMerchantCode
                    ImgForm.three.channelMerchantCode = nowRes.data.channelMerchantCode
                }, 300)
            }
        } else {
            ElMessage({
                type: "error",
                message: channelForm.id ? "渠道商编辑失败 请重试！" : "编辑商新增失败 请重试！"
            })
        }
    })


}

const resetForm = () => {
    ruleFormRef.value?.resetFields()
}
const proChange = (val: any) => {
    console.log(val);
    province.value.some(item => {
        if (val == item.dictItemCode) {
            filterData(1, item.id)
            channelForm.locationProvinceName = item.dictItemName
            channelForm.locationCityCode = null
            channelForm.locationCityName = null
            return
        }
    })

}
const proChange1 = (val: any) => {
    console.log(val);
    selectProvinceCity.value.some(item => {
        if (val == item.dictItemCode) {
            channelForm.locationCityName = item.dictItemName
            return
        }
    })
}
const nextSetp = () => {
    active.value--
}
const file1 = async (file: any) => {
    console.log(file);

    if (file.length) {
        const formData = new FormData()
        formData.append("file", file[0])
        formData.append("param", JSON.stringify({ module: "channelMerchant", type: "1" }))

        const res = await attachmentUploadApiPost(formData)
        if (res.code == 20000) {
            ImgForm.one.attachmentName = res.data.attachmentName
            ImgForm.one.attachmentAliasName = res.data.attachmentAliasName
            ImgForm.one.attachmentUri = res.data.attachmentUri
            imgUpload1.value.newUrl(res.data.attachmentUri, false)
            //  merchantSaveOrUpdateAttachmentApiPost
            saveAttachement(1)

        }
    } else {
        ImgForm.one.attachmentName = null
        ImgForm.one.attachmentAliasName = null
        ImgForm.one.attachmentUri = null
        const dele = await merchantDeleteAttachmentApiDelete({ id: blackSuccess.value.one })
        if (dele.code == 20000) {
            ElMessage({
                type: "success",
                message: "法人身份证正面照片删除成功"
            })
        }

    }
}
const file2 = async (file: any) => {
    if (file.length) {
        const formData = new FormData()
        formData.append("file", file[0])
        formData.append("param", JSON.stringify({ module: "channelMerchant", type: "2" }))

        const res = await attachmentUploadApiPost(formData)
        if (res.code == 20000) {
            ImgForm.two.attachmentName = res.data.attachmentName
            ImgForm.two.attachmentAliasName = res.data.attachmentAliasName
            ImgForm.two.attachmentUri = res.data.attachmentUri
            imgUpload2.value.newUrl(res.data.attachmentUri, false)
            saveAttachement(2)

        }
    } else {
        ImgForm.two.attachmentName = null
        ImgForm.two.attachmentAliasName = null
        ImgForm.two.attachmentUri = null
        const dele = await merchantDeleteAttachmentApiDelete({ id: blackSuccess.value.two })

        if (dele.code == 20000) {
            ElMessage({
                type: "success",
                message: "法人身份证反面照片删除成功"
            })
        }
    }

}
const file3 = async (file: any) => {
    if (file.length) {
        const formData = new FormData()
        formData.append("file", file[0])
        formData.append("param", JSON.stringify({ module: "channelMerchant", type: "3" }))

        const res = await attachmentUploadApiPost(formData)
        if (res.code == 20000) {
            ImgForm.three.attachmentName = res.data.attachmentName
            ImgForm.three.attachmentAliasName = res.data.attachmentAliasName
            ImgForm.three.attachmentUri = res.data.attachmentUri
            imgUpload3.value.newUrl(res.data.attachmentUri, false)
            saveAttachement(3)

        }
    } else {
        ImgForm.three.attachmentName = null
        ImgForm.three.attachmentAliasName = null
        ImgForm.three.attachmentUri = null
        const dele = await merchantDeleteAttachmentApiDelete({ id: blackSuccess.value.three })
        if (dele.code == 20000) {
            ElMessage({
                type: "success",
                message: "营业执照删除成功"
            })
        }
    }

}
const saveAttachement = async (types: number) => {
    //  merchantSaveOrUpdateAttachmentApiPost
    try {
        let res: any = null
        if (types == 1) {
            res = await merchantSaveOrUpdateAttachmentApiPost(ImgForm.one)
            // 后期删除 数据保存一哈
            blackSuccess.value.one = res.data
        } else if (types === 2) {
            res = await merchantSaveOrUpdateAttachmentApiPost(ImgForm.two)
            blackSuccess.value.two = res.data
        } else if (types === 3) {
            res = await merchantSaveOrUpdateAttachmentApiPost(ImgForm.three)
            blackSuccess.value.three = res.data
        }
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: types == 1 ? "法人身份证正面照片上传成功" : types == 2 ? "法人身份证反面照片上传成功" : "营业执照上传成功"
            })
        }
    } catch (error) {

    }
}
const onConfirmImg = () => {
    onClose()
    if(addOrEdit.value == 'add'){
        console.log('add');
        
        emit('refresh')
    }else {
        emit('searchEdit')
        console.log('edit');
    }
    return ElMessage({
        type: "success",
        message: channelForm.id ? "渠道商编辑数据成功" : "渠道商基础数据成功！"
    })

}
defineExpose({
    show
})
</script>

<template>
    <SysDialogSlot :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :draggable="true"
        :margin-top="dialogBasic.marginTop" @on-close="onClose" destroy-on-close @on-confirm="onConfirm">
        <template v-slot:content>
            <div style="margin: 10px 0px;">
                <el-steps :active="active" finish-status="success" align-center>
                    <el-step title="渠道商基础信息" />
                    <el-step title="渠道商附件上传" />
                </el-steps>
            </div>
            <el-form ref="ruleFormRef" :model="channelForm" :rules="rules" label-width="150px" class="demo-ruleForm"
                status-icon v-show="active === 0">


                <el-form-item label="渠道商类型" prop="channelMerchantType">
                    <BlackSelect v-model:select-value="channelForm.channelMerchantType" :options="productType">
                    </BlackSelect>

                </el-form-item>

                <el-form-item label="渠道商名称" prop="channelMerchantName">
                    <el-input v-model="channelForm.channelMerchantName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="渠道商联系人" prop="contactName">
                    <el-input v-model="channelForm.contactName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="联系人手机号" prop="contactMobile">
                    <el-input v-model="channelForm.contactMobile" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="渠道商法人" prop="corporationName">
                    <el-input v-model="channelForm.corporationName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="渠道商法人证件号" prop="corporationCertNo">
                    <el-input v-model="channelForm.corporationCertNo" maxlength="18" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="所在地-省" prop="locationProvinceCode">
                    <el-select v-model="channelForm.locationProvinceCode" @change="proChange" placeholder="请选择所在省份">
                        <el-option v-for="item in province" :key="item.id" :label="item.dictItemName"
                            :value="item.dictItemCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所在地-市" prop="locationCityCode">
                    <el-select v-model="channelForm.locationCityCode" @change="proChange1" placeholder="请选择所在市">
                        <el-option v-for="item in selectProvinceCity" :key="item.id" :label="item.dictItemName"
                            :value="item.dictItemCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="统一社会信用代码" prop="uscc">
                    <el-input v-model="channelForm.uscc" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="channelForm.remarks" placeholder="请输入" />
                </el-form-item>
            </el-form>



            <el-form ref="ruleImgRef" :model="ImgForm" style="margin-top: 50px;" label-width="200px"
                class="demo-ruleForm" status-icon v-show="active === 1">
                <el-form-item label="法人身份证正面照片">
                    <upLoadImgSingle ref="imgUpload1" @fileUp="file1"></upLoadImgSingle>
                </el-form-item>
                <el-form-item label="法人身份证反面照片">
                    <upLoadImgSingle ref="imgUpload2" @fileUp="file2"></upLoadImgSingle>
                </el-form-item>
                <el-form-item label="营业执照">
                    <upLoadImgSingle ref="imgUpload3" @fileUp="file3"></upLoadImgSingle>
                </el-form-item>

            </el-form>

        </template>

        <template v-slot:myFooter>
            <div class="dialog-footer">
                <el-button @click="onClose">取消</el-button>
                <el-button @click="nextSetp" v-if="active !== 0">上一步</el-button>
                <el-button type="success" @click="onConfirm" v-if="active === 0">下一步</el-button>
                <el-button type="success" @click="onConfirmImg" v-if="active === 1">确定</el-button>
            </div>
        </template>

    </SysDialogSlot>
</template>

<style lang='scss' scoped>
.my-header {
    height: 48px;
    font-size: 18px;
}
</style>
